package com.cscec5b.inspection.controller;


import com.cscec5b.inspection.entity.RebarRecord;
import com.cscec5b.inspection.service.PdfRenderService;
import com.cscec5b.inspection.service.RebarRecordAppService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/rebar")
public class RebarRecordController {

    private final RebarRecordAppService app;
    private final PdfRenderService pdfRenderService;

    public RebarRecordController(RebarRecordAppService app, PdfRenderService pdfRenderService) {
        this.app = app; this.pdfRenderService = pdfRenderService;
    }

    @PostMapping("/save")
    public Map<String,Object> save(@RequestBody RebarRecord body){ return app.save(body); }

    @GetMapping("/{id}")
    public Map<String,Object> detail(@PathVariable long id){ return app.detail(id); }

    @GetMapping("/project/{projectId}")
    public List<RebarRecord> list(@PathVariable long projectId){ return app.listByProject(projectId); }

    // ===== 导出 PDF =====
    @GetMapping("/{id}/export")
    public ResponseEntity<byte[]> export(@PathVariable long id,
                                         @RequestParam(required = false) String projectName) {

        Map<String,Object> res = app.detail(id);
        Object dataObj = res.get("data");
        if (dataObj == null) return ResponseEntity.notFound().build();

        RebarRecord rec = (dataObj instanceof RebarRecord)
                ? (RebarRecord) dataObj
                : new ObjectMapper().convertValue(dataObj, RebarRecord.class);

        Map<String,Object> data = new HashMap<>();
        data.put("title", "钢筋连接接头安装施工质量检查验收记录");
        data.put("projectName", projectName == null ? "" : projectName);
        data.put("constructionUnit", nz(rec.getConstructionUnit()));
        data.put("serialNo", nz(rec.getSerialNo()));
        data.put("rebarSpec", nz(rec.getRebarSpec()));
        data.put("jointCount", rec.getJointCount()==null? "": String.valueOf(rec.getJointCount()));
        data.put("performanceLevel", nz(rec.getPerformanceLevel()));
        data.put("operatorName", nz(rec.getOperatorName()));
        data.put("cutSpecResult", nz(rec.getCutSpecResult()));
        data.put("mechSpecResult", nz(rec.getMechSpecResult()));
        data.put("installStart", fmt(rec.getInstallDateS()));
        data.put("installEnd",   fmt(rec.getInstallDateE()));
        data.put("position", nz(rec.getPosition()));
        data.put("standard", nz(rec.getStandard()));
        data.put("appearanceCheck", nz(rec.getAppearanceCheck()));
        data.put("pressValues", joinNums(rec.getPressValues()));

        data.put("constructionEvaluation", nz(rec.getConstructionEvaluation()));
        data.put("supervisorConclusion", nz(rec.getSupervisorConclusion()));
        data.put("remark", nz(rec.getRemark()));

        data.put("techLeaderName", nz(rec.getTechLeaderName()));
        data.put("techLeaderDate", rec.getTechLeaderDate()==null?"":rec.getTechLeaderDate().toString());
        data.put("supervisorEngineerName", nz(rec.getSupervisorEngineerName()));
        data.put("supervisorEngineerDate", rec.getSupervisorEngineerDate()==null?"":rec.getSupervisorEngineerDate().toString());
        data.put("recorder", nz(rec.getRecorder()));
        data.put("projectDeptSealDate", rec.getProjectDeptSealDate()==null?"":rec.getProjectDeptSealDate().toString());

        data.put("projectId", rec.getProjectId()==null?0:rec.getProjectId());

        // 检查项
//        data.put("checklistData", rec.getChecklist()==null? List.of() : rec.getChecklist());
        data.put("checklist", rec.getChecklist()==null? List.of() : rec.getChecklist());
        byte[] pdf = pdfRenderService.renderWithFont(
                "templates/rebar_record.html",
                data,
                "fonts/simhei.ttf",     // 放一个含中文字形的 OTF/TTF
                "custom"
        );

        String fn = URLEncoder.encode("钢筋接头安装质量检查记录_" + id + ".pdf", StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''"+fn)
                .contentType(MediaType.APPLICATION_PDF)
                .body(pdf);
    }

    // ---- helpers ----
    private static String fmt(LocalDateTime dt){ return dt==null? "": dt.toString().replace('T',' '); }
    private static String nz(String s){ return s==null? "": s; }
    private static String joinNums(List<? extends Number> list){
        if (list==null || list.isEmpty()) return "";
        return list.stream().map(x -> x==null? "": String.valueOf(x)).collect(Collectors.joining("、"));
    }
}
